package ar.com.fracervellera.web.controller;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.com.fracervellera.model.PMF;
import ar.com.fracervellera.model.Project;
import ar.com.fracervellera.server.services.ProjectService;
import ar.com.fracervellera.server.services.ProjectServiceImp;

public class Home extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PersistenceManager pm ;
	private ProjectService projectService = ProjectServiceImp.GetInstance();
	private static final Logger log = Logger.getLogger("LoggerHome");
	

	@Override
	public void init() throws ServletException {
		super.init();
		pm = PMF.get().getPersistenceManager();
		
	}
	
	@Override
	public void destroy() {
		super.destroy();
		if(pm != null && !pm.isClosed()){
			pm.close();
		}
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<Project> projects = projectService.getLastProjects(pm);
		List<Project> lastProjects = new LinkedList<Project>(); 
		if(projects != null && !projects.isEmpty()) {
			int i = 0;
			for(Project current : projects){
				if( i < 3) {
					i++;
					lastProjects.add(current);
				}
			}
		}
		if(projects != null && !projects.isEmpty()){
			req.setAttribute("project_list", lastProjects);
			req.setAttribute("first_project", projects.get(0));
		}
		req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
	}
}
